package softswitch.service;

import java.util.List;

import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import softswitch.model.Plan;
import softswitch.model.PlanDetail;
import softswitch.model.Route;


@Stateless
public class PlanDetailDAO {

	
	@PersistenceContext(unitName = "persistence")
    private EntityManager em;
	
	
	public PlanDetail getById(Integer id){	
		return em.find(PlanDetail.class, id);
	}
	
    public PlanDetail save(PlanDetail plandetail) {
    	em.persist(plandetail); 
    	return plandetail;
    }
    
    public PlanDetail update(PlanDetail plandetail) {
    	return em.merge(plandetail);
    }
    
    public void delete(Integer id) {
    	em.remove(em.find(PlanDetail.class, id));	
    }
    
    @SuppressWarnings("unchecked")
    public List<PlanDetail> list(int first, int max) {    	
    	Query query = em.createQuery("SELECT e FROM PlanDetail");
    	if (max > 0) {
            query.setMaxResults(max);
        }
        if (first > 0) {
            query.setFirstResult(first);
        }
        return query.getResultList();   
    }
    
    //---------------------------------------------------------------------------------
    
    @SuppressWarnings("unchecked")
    public List<PlanDetail> listByPlan(Plan plan) {    	
    	List<PlanDetail> results = null;
    	Query query = em.createQuery("SELECT e FROM PlanDetail e WHERE e.plan=:plan");
		query.setParameter("plan", plan);
		try {
			results = query.getResultList(); 
        }
    	catch (Exception e) {
			//e.printStackTrace();
		}
        return results;
    }
    
    public PlanDetail getByPlanRoute(Plan plan, Route route) {    	
    	PlanDetail result = null;
    	Query query = em.createQuery("SELECT e FROM PlanDetail e WHERE e.plan=:plan AND e.route=:route");
		query.setParameter("plan", plan);
		query.setParameter("route", route);
		try {
			result = (PlanDetail) query.getSingleResult(); 
        }
    	catch (Exception e) {
			//e.printStackTrace();
		}
        return result;
    }
    
}